package com.red.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.red.context.BaseContext;
import com.red.dto.HomePageQueryDTO;
import com.red.dto.NotesUploadDTO;
import com.red.dto.TravelNotesDTO;
import com.red.dto.commentPageQueryDTO;
import com.red.entity.NoteComments;
import com.red.entity.TravelNotes;
import com.red.entity.Users;
import com.red.entity.UsersTravelNotes;
import com.red.exception.BaseException;
import com.red.mapper.NoteCommentsMapper;
import com.red.mapper.TravelNotesMapper;
import com.red.mapper.UserMapper;
import com.red.mapper.UsersTravelNotesMapper;
import com.red.result.PageResult;
import com.red.service.TravelNotesService;
import com.red.utils.SensitiveWordFilter;
import com.red.vo.CommentAllVO;
import com.red.vo.NoteCommentsVO;
import com.red.vo.NotesVO;
import com.red.vo.TravelNotesVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.sl.usermodel.Notes;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;


@Service
@Slf4j
public class TravelNotesServiceImpl extends ServiceImpl<TravelNotesMapper, TravelNotes> implements TravelNotesService {
    @Autowired
    private TravelNotesMapper travelNotesMapper;
    @Autowired
    private NoteCommentsMapper noteCommentsMapper;
    @Autowired
    private UsersTravelNotesMapper usersTravelNotesMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private SensitiveWordFilter sensitiveWordFilter;

    /**
     * 分页查询
     * @return
     */
    public PageResult pageQuery(HomePageQueryDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());

        List<NotesVO> notesVOList = travelNotesMapper.pageQuery(dto);

        PageInfo<NotesVO> pageInfo = new PageInfo<>(notesVOList);

        //封装小记的评论信息
        List<NotesVO> list = pageInfo.getList();
        ArrayList<List<NoteCommentsVO>> arrayList = new ArrayList<>();

        QueryWrapper<UsersTravelNotes> qw = new QueryWrapper<>();
        qw.eq("user_id",BaseContext.getCurrentId());

        for (NotesVO notesVO : list) {
            //查找所有评论 以及评论人的信息
            List<NoteCommentsVO> vo = noteCommentsMapper.all(notesVO.getId());
            notesVO.setCommentslist(vo);
            //判断该用户是否点赞该小记
            qw.eq("travel_notes_id",notesVO.getId());
            UsersTravelNotes usersTravelNotes = usersTravelNotesMapper.selectOne(qw);
            if (usersTravelNotes == null) {
                notesVO.setStatus(false);
            } else {
                notesVO.setStatus(true);
            }
        }


        return new PageResult(pageInfo.getTotal(),pageInfo.getList());
    }

    /**
     * 小记上传
     * @param dto
     */
    public void uploadNote(NotesUploadDTO dto) {
        TravelNotes travelNotes = new TravelNotes();
        BeanUtils.copyProperties(dto,travelNotes);

        travelNotes.setUserId(BaseContext.getCurrentId());
        travelNotes.setCreatedAt(LocalDateTime.now());
        travelNotes.setLikeNumber(0L);
        travelNotes.setPublish(0);
        travelNotes.setApproveStatus(0);
        travelNotesMapper.insert(travelNotes);
    }

    /**
     * 根据ID删除小记
     * @param ids
     */
    @Transactional
    public void deleteByIds(List<Long> ids) {
        //删除小记
        travelNotesMapper.deleteByIds(ids);
        //删除小记用户喜欢表
        HashMap<String , Object> map = new HashMap<>();
        map.put("travel_notes_id",ids);
        usersTravelNotesMapper.deleteByMap(map);
        //删除小记的评论表
        QueryWrapper<NoteComments> qw = new QueryWrapper<>();
        HashMap<String , Object> map1 = new HashMap<>();
        map1.put("note_id",ids);
        noteCommentsMapper.deleteByMap(map1);
    }

    /**
     * 给小记点赞
     * @param id
     */
    @Transactional
    public void noteLike(Long id) {
        //小记数增加1
        TravelNotes travelNotes = travelNotesMapper.selectById(id);
        if(travelNotes == null){
            throw new BaseException("点赞失败");
        }

//设置用户小记关联表
        UsersTravelNotes usersTravelNotes = new UsersTravelNotes();
        usersTravelNotes.setUserId(BaseContext.getCurrentId());

        usersTravelNotes.setTravelNotesId(id);

//判断是点赞还是取消点赞
        QueryWrapper<UsersTravelNotes> qw = new QueryWrapper<>();
        qw.eq("user_id",BaseContext.getCurrentId());
        qw.eq("travel_notes_id",id);
        UsersTravelNotes result = usersTravelNotesMapper.selectOne(qw);
        if (result == null){
            //说明没有点赞记录 此操作是点赞
            usersTravelNotesMapper.insert(usersTravelNotes);
            travelNotes.setLikeNumber(travelNotes.getLikeNumber()+1);
            travelNotesMapper.updateById(travelNotes);
        }else {
            //说明有点赞记录 此操作是取消点赞
            usersTravelNotesMapper.deleteById(result);
            travelNotes.setLikeNumber(travelNotes.getLikeNumber()-1);
            travelNotesMapper.updateById(travelNotes);
        }

    }

    /**
     * 根据用户Id查询
     * @return
     */
    public List<TravelNotes> selectByUserId() {
        HashMap<String , Object> map = new HashMap<>();
        Long userId = BaseContext.getCurrentId();
        map.put("user_id",userId);
        //查询喜欢的小记ID
        List<UsersTravelNotes> usersTravelNotes = usersTravelNotesMapper.selectByMap(map);

        if (usersTravelNotes == null || usersTravelNotes.isEmpty()){
            //如果为空直接返回空对象
            return new ArrayList<TravelNotes>();
        }else {
            //否则查询返回
            List<Long> travelNotesIds = usersTravelNotes.stream().map(UsersTravelNotes::getTravelNotesId).collect(Collectors.toList());
            List<TravelNotes> list = travelNotesMapper.selectByIds(travelNotesIds);
            return list;
        }
    }

    /**
     * 根据ID查询小记
     * @param id
     * @return
     */
    public NotesVO selectById(Long id) {
        TravelNotes travelNotes = travelNotesMapper.selectById(id);
        NotesVO notesVO = new NotesVO();
        BeanUtils.copyProperties(travelNotes,notesVO);

        //查找用户头像昵称
        Users users = userMapper.selectById(BaseContext.getCurrentId());
        notesVO.setNickname(users.getNickname());
        notesVO.setAvatarUrl(users.getAvatarUrl());

        QueryWrapper<UsersTravelNotes> qw = new QueryWrapper<>();
        qw.eq("user_id",BaseContext.getCurrentId());

        //查找所有评论 以及评论人的信息
        List<NoteCommentsVO> vo = noteCommentsMapper.all(notesVO.getId());
        notesVO.setCommentslist(vo);
        //判断该用户是否点赞该小记
        qw.eq("travel_notes_id",notesVO.getId());
        UsersTravelNotes usersTravelNotes = usersTravelNotesMapper.selectOne(qw);
        if (usersTravelNotes == null) {
            notesVO.setStatus(false);
        } else {
            notesVO.setStatus(true);
        }
        return notesVO;
    }

    /**
     * 根据用户id查询发布的小记
     * @return
     */
    public List<NotesVO> selectAllByUserId() {
        List<NotesVO> arrayList = new ArrayList<>();

        QueryWrapper<TravelNotes> qw = new QueryWrapper<>();
        qw.eq("user_id",BaseContext.getCurrentId());
        List<TravelNotes> list = travelNotesMapper.selectList(qw);
        for (TravelNotes travelNotes : list) {
            NotesVO notesVO = new NotesVO();
            BeanUtils.copyProperties(travelNotes,notesVO);

            QueryWrapper<UsersTravelNotes> qw1 = new QueryWrapper<>();
            qw1.eq("user_id",BaseContext.getCurrentId());

            //查找所有评论 以及评论人的信息
            List<NoteCommentsVO> vo = noteCommentsMapper.all(notesVO.getId());
            notesVO.setCommentslist(vo);
            //判断该用户是否点赞该小记
            qw1.eq("travel_notes_id",notesVO.getId());
            UsersTravelNotes usersTravelNotes = usersTravelNotesMapper.selectOne(qw1);
            if (usersTravelNotes == null) {
                notesVO.setStatus(false);
            } else {
                notesVO.setStatus(true);
            }
            arrayList.add(notesVO);
        }
        return arrayList;
    }

    /**
     * 发表评论
     * @param noteComments
     */
    public void uploadComment(NoteComments noteComments) {
        // 过滤敏感词
        String filteredContent = sensitiveWordFilter.filter(noteComments.getContent());
        noteComments.setUserId(BaseContext.getCurrentId());
        noteComments.setTime(LocalDateTime.now());
        noteComments.setContent(filteredContent);
        noteCommentsMapper.insert(noteComments);
    }

    /**
     * 审批
     * @param travelNotes
     */
    public void approval(TravelNotes travelNotes) {
        travelNotes.setApproveStatus(1);
        travelNotesMapper.updateById(travelNotes);
    }

    /**
     * 管理员分页查询
     * @param dto
     * @return
     */
    public PageResult adminPageQuery(TravelNotesDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());

        Page<TravelNotesVO> page = travelNotesMapper.adminPageQuery(dto);

        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 分页查询所有评论
     * @return
     */
    public PageResult commentPageQuery(commentPageQueryDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());

        Page<CommentAllVO> page = travelNotesMapper.commentPageQuery(dto);
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 根据评论Id删除评论
     * @param ids
     */
    @Override
    public void deleteCommentByIds(List<Long> ids) {
        noteCommentsMapper.deleteByIds(ids);
    }
}
